package cc.aliza.lib.mongo.core.decoder;

import cc.aliza.lib.mongo.core.AlizaEntity;
import cc.aliza.lib.mongo.core.InternalDao;
import cc.aliza.lib.mongo.core.annotations.Default;
import cc.aliza.lib.mongo.core.annotations.Ref;
import cc.aliza.lib.mongo.core.cache.ConstructorCache;
import cc.aliza.lib.mongo.core.cache.DaoCache;
import cc.aliza.lib.mongo.core.utils.FieldUtil;
import cc.aliza.lib.mongo.core.utils.ReferenceUtil;
import org.bson.Document;

import java.lang.reflect.Field;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public class RefDecoder extends AbstractDecoder {

    private boolean cascadeR;

    public RefDecoder(Document document, Field field) {
        super(field);
        Ref ref = field.getAnnotation(Ref.class);
        value = document.get(getFieldRealName(ref.name()));
        String cascade = ref.cascade().toUpperCase();
        cascadeR = cascade.contains(Default.CASCADE_READ);
    }

    @Override
    public void decode(Object obj) {
        String id = ReferenceUtil.fromDBRef(value);
        Class<?> clazz = FieldUtil.getRealType(field, value);
        AlizaEntity entity;
        if (cascadeR) {
            InternalDao dao = DaoCache.getInstance().get(clazz);
            entity = (AlizaEntity) dao.findOne(id);
        } else {
            entity = (AlizaEntity) ConstructorCache.getInstance().get(clazz);
            entity.setId(id);
        }
        FieldUtil.set(obj, field, entity);
    }
}
